package cn.tedu.article1.common.exception;

import cn.tedu.article1.common.response.JsonResult;
import cn.tedu.article1.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult toHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();

        log.error("MethodArgumentNotValidException: " + data);

        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult toHandlerConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();

        log.error("ConstraintViolationException: " + data);

        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult toHandlerThrowable(Throwable ex){
        String data = ex.getMessage();

        log.error("Throwable: " + data);

        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }
}
